var editor; // use a global for the submit and return data rendering
var table;
var userTypeId=0;
var user;
var communityId="";

function getUrl(url,params) {
    for (var i=0;i<params.length;i++){
        if ($("#"+params[i]).val()!= "") {
            url = url + "&"+params[i]+"=" + $("#"+params[i]).val();
        }
    }
    return url;

}
$(document).ready(function () {
    var areaUrl ="/commis/api/house/sumArea?1=1";
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                console.log("用户存在");
                user =response.data;
                userTypeId=user.userTypeId;
                if(userTypeId==4){
                    communityId=user.communityId;
                    areaUrl=areaUrl+"&communityId="+communityId;
                }
                console.log(userTypeId);
            } else if (response.status==1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        },error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })

    $.ajax({
        url: '/commis/api/community/all',
        async: false,
        dataType: 'json',
        success: function (response) {
            for (var i = 0; i < response.length; i++) {
                $("#community").append("<option value='" + response[i].communityId + "'>" + response[i].communityName + "</option>");
            }

        }, error: function () {
            alert("发生错误");
            window.parent.location.href = "../../login.html";
        }
    });
    $.ajax({
        url: areaUrl,
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                $("#areaSpan").html(response.data.toFixed(2))
            } else if (response.status==1) {
                alert("获取面积错误");
            }
        },error: function (msg) {
            alert("发生错误了");
        }
    });


    $.ajax({
        url: "/commis/api/setting/getValueByName",
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

            name:"用房情况"

        },
        success: function (response) {
            if (response.status==0) {

                var value =response.data;
                var fields=[
                    {
                        label: "所属社区:",
                        name: "communityId",
                        type: "select"
                    }, {
                        label: "用房地址:",
                        name: "houseAdd"
                    }, {
                        label: "房屋面积:",
                        name: "houseArea"
                    }, {
                        label: "起用时间:",
                        name: "completedTime",
                        type: 'datetime',
                        def: function () {
                            return new Date();
                        }
                    }, {
                        label: "当下用途:",
                        name: "serviceCondition",
                        type: "select",
                        options: ["","办公用房", "图书馆", "多功能室"]
                    }, {
                        label: "取得方式:",
                        name: "acquireWay",
                        type: "select",
                        options: [
                            {
                                label: "配套",
                                value: "1"
                            }, {
                                label: "购置",
                                value: "2"
                            }, {
                                label: "新建、改扩建",
                                value: "3"
                            }, {
                                label: "租用",
                                value: "4"
                            }, {
                                label: "无偿使用",
                                value: "5"
                            }, {
                                label: "共享",
                                value: "6"
                            }, {
                                label: "其他",
                                value: "7"
                            }
                        ]
                    }, {
                        label: "购置时间:",
                        name: "buyDate",
                        type: 'datetime',
                        def: function () {
                            return new Date();
                        }

                    }, {
                        label: "钱数:",
                        name: "money"

                    }, {
                        label: "产权归属:",
                        name: "houseName"
                    } ,{
                        label: "资金来源:",
                        name: "fundFrom"
                    }, {
                        label: "备注:",
                        name: "remarks"
                    }
                ];
                if(userTypeId==4){
                    fields.shift();
                }
                editor = new $.fn.dataTable.Editor({
                    ajax: {
                        create: {
                            type: 'POST',
                            url: '/commis/api/house/create'
                        },
                        edit: {
                            type: 'PUT',
                            url: '/commis/api/house/edit?id=_id_'
                        },
                        remove: {
                            type: 'DELETE',
                            url: '/commis/api/house/remove?id=_id_'
                        }
                    },
                    i18n: {
                        create: {
                            title: "新增记录",
                            submit: "添加"
                        },
                        edit: {
                            title: "修改记录",
                            submit: "修改",
                            confirm: "您确定要修改这 %d 条记录吗?"
                        },
                        remove: {
                            title: "删除记录",
                            submit: "删除",
                            confirm: "您确定要删除这 %d 条记录吗?"
                        }
                    },
                    idSrc: 'houseId',
                    table: "#houseTable",
                    fields: fields
                });

                /*   editor.on('preSubmit', function (e, d, action) {
                 console.log(action)
                 if (action == "remove") {
                 console.log("remove----")
                 return true;
                 }
                 var houseAddField = this.field('houseAdd');
                 var timeField = this.field('registerTime');
                 var houseNameField = this.field('houseName');
                 var houseAreaField = this.field('houseArea');
                 var houseTypeField = this.field('houseType');
                 var completedTimeField = this.field('completedTime');

                 if (houseNameField.val() === '') {
                 houseNameField.error('用房名称不能为空');
                 return false;
                 }
                 if (houseAddField.val() === '') {
                 houseAddField.error('用房地址不能为空');
                 return false;
                 }
                 var strInputDate = completedTimeField.val();
                 if (strInputDate === '') {
                 completedTimeField.error('建成时间不能为空');
                 return false;
                 } else {

                 if (strInputDate.indexOf("-") <= 0) {
                 completedTimeField.error('建成时间请输入合法的日期格式：yyyy-mm-dd');
                 return false;
                 }
                 strInputDate = strInputDate.replace(/-/g, "/");
                 var d = new Date(strInputDate);
                 if (isNaN(d)) return false;
                 var arr = strInputDate.split("/");
                 if (!(parseInt(arr[0], 10) == d.getFullYear()) && (parseInt(arr[1], 10) == (d.getMonth() + 1)) && (parseInt(arr[2], 10) == d.getDate())) {
                 completedTimeField.error('建成时间请输入合法的日期格式：yyyy-mm-dd');
                 return false;
                 }
                 }
                 strInputDate = timeField.val();
                 if (strInputDate === '') {
                 timeField.error('填报时间不能为空');
                 return false;
                 } else {

                 if (strInputDate.indexOf("-") <= 0) {
                 timeField.error('填报时间请输入合法的日期格式：yyyy-mm-dd');
                 return false;
                 }
                 strInputDate = strInputDate.replace(/-/g, "/");

                 var d = new Date(strInputDate);
                 if (isNaN(d)) return false;
                 var arr = strInputDate.split("/");
                 if (!(parseInt(arr[0], 10) == d.getFullYear()) && (parseInt(arr[1], 10) == (d.getMonth() + 1)) && (parseInt(arr[2], 10) == d.getDate())) {
                 timeField.error('填报时间请输入合法的日期格式：yyyy-mm-dd');
                 return false;
                 }

                 }

                 if (houseAreaField.val() === '') {
                 houseAreaField.error('面积不能为空');
                 return false;
                 }
                 if (houseTypeField.val() === '') {
                 houseTypeField.error('用房类别不能为空');
                 return false;
                 }

                 return true;
                 });*/



                var buttons = [];
                var select = true;
                if (userTypeId == 1) {
                    $(".communityDiv").show();
                    select = true;
                    buttons = [
                        {extend: "create", editor: editor, text: "添加", className: 'btn btn-primary'},
                        {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
                        {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
                    ];
                    console.log(buttons);


                } else if (userTypeId == 2) {
                    $(".communityDiv").show();
                    select = true;
                    buttons = [
                        {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
                        {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
                    ];

                } else if (userTypeId == 3||userTypeId == 6||userTypeId == 7||userTypeId == 8||userTypeId == 9) {
                    $(".communityDiv").show();
                    select = false;
                    buttons = [];

                } else if (userTypeId == 4) {
                    $(".communityDiv").hide();
                    if(value==1){
                        select = true;
                        buttons = [ {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'}];
                    }else{
                        select = false;
                        buttons = [];
                    }


                }else if (userTypeId ==5) {
                    $(".communityDiv").hide();
                    select = false;
                    buttons = [];

                }

                editor.dependent('acquireWay', function (val) {
                    console.log(val);

                    if(val=== "2"){
                        return  {show: ['buyDate','money']}
                    }else if(val === "4"){
                        return  {show: ['money'],hide: ['buyDate']}
                    }else{
                        return {hide: ['money','buyDate']}
                    }

                });




                table = $('#houseTable').DataTable({

                    dom: "Bfrtip",
                    ajax: "/commis/api/house/pageDatatables?communityId="+communityId,
                    autoWidth:true,
                    responsive: true,
                    pageLength: 10,


                    serverSide: true,
                    processing: true,
                    lengthChange: false,//是否允许用户改变表格每页显示的记录数
                    ordering: false,//是否允许用户排序
                    paging: true,//是否分页
                    pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
                    searching: false,//是否开始本地搜索
                    stateSave: false,//刷新时是否保存状态
                    autoWidth: true,//自动计算宽度
                    language: {
                        emptyTable: "没有数据",
                        search: "搜索:",
                        paginate: {
                            first: "首页",
                            previous: "上一页",
                            next: "下一页",
                            last: "尾页"

                        },
                        select: {
                            rows: {
                                _: "选中 %d 行",
                                1: "选中 1 行"
                            },
                            columns: "选中 %d 列"
                        },
                        lengthMenu: "每页 _MENU_ 条记录",
                        zeroRecords: "没有找到记录",
                        info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
                        infoEmpty: "无记录",
                        infoFiltered: "(从 _MAX_ 条记录过滤)"
                    },
                    columns: [
                        {
                            data: 'community.communityName', defaultContent: ""
                        },
                        {
                            data: 'houseAdd', defaultContent: ""
                        },{
                            data: 'houseArea', defaultContent: ""
                        }, {
                            data: 'completedTime', defaultContent: ""
                        }, {
                            data: 'serviceCondition', defaultContent: ""
                        }, {
                            data: 'acquireWay',
                            render: function (data, type, row) {

                                if (1 == data) {
                                    return "配套";
                                } else if (2 == data){
                                    if(row.buyDate){
                                        if(row.money){
                                            return "购置"+"（时间："+row.buyDate+" 金额："+row.money+"）"
                                        }else {
                                            return "购置"+"（时间："+row.buyDate+"）"
                                        }

                                    }else{
                                        if(row.money){
                                            return "购置"+"（金额："+row.money+"）"
                                        }else {
                                            return "购置";
                                        }
                                    }
                                    return "购置"+"（"+row.money+"）"
                                }else if (3 == data){
                                    return "新建、改扩建"
                                }else if (4 == data){
                                    if(row.money){
                                        return "租用"+"（金额："+row.money+"）"
                                    }else {
                                        return "租用";
                                    }
                                }else if (5 == data){
                                    return "无偿使用"
                                }else if (6 == data){
                                    return "共享"
                                }else {
                                    return "其他"
                                }
                            }
                        }, {
                            data: 'houseName', defaultContent: ""
                        }, {
                            data: 'fundFrom', defaultContent: ""
                        }, {
                            data: 'remarks', defaultContent: ""
                        }, {
                            data: 'registerTime', defaultContent: ""
                        }, {
                            data: 'user.realName', defaultContent: ""
                        }],
                    select: select,
                    buttons: buttons

                });
            } else if (response.status==1) {
                alert("没有数据");
            }
        },error: function (msg) {
            alert("发生错误了");
        }
    })


    $('#completedTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true,


    });

    $('#registerTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true


    });




    $('#search').on('click', function () {

        var url = "/commis/api/house/pageDatatables?1=1"

        if(userTypeId!=4){
             communityId = $('#community').val();

        }
        var addUrl =  "&communityId=" + communityId;

       var params=["houseAdd","acquireWay","houseName","registerTime","fundFrom","orderName"];
        addUrl=getUrl(addUrl,params);
        url =url+addUrl;

       var areaUrl="/commis/api/house/sumArea?1=1";
       areaUrl =areaUrl+addUrl;
        $.ajax({
            url: areaUrl,
            type: "GET",
            async: false,
            dataType: 'json',
            data: {

            },
            success: function (response) {
                if (response.status==0) {
                 $("#areaSpan").html(response.data.toFixed(2))
                } else if (response.status==1) {
                    alert("发生错误");
                }
            },error: function (msg) {
                alert("发生错误了");
            }
        })



        table.ajax.url(url).load();

    });




})

//设置框架
$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});